<template>
  <div 
    :class="[
      'bx-cascader',
      'bx-glass',
      {
        'bx-cascader--disabled': disabled,
        'bx-cascader--focused': showDropdown
      }
    ]"
    v-click-outside="handleClickOutside"
  >
    <div 
      class="bx-cascader__input"
      @click="toggleDropdown"
    >
      <input
        type="text"
        :value="displayValue"
        :placeholder="placeholder"
        :disabled="disabled"
        readonly
        class="bx-cascader__input-field"
      />
      <BxIcon name="chevron-down" class="bx-cascader__arrow" />
      <BxIcon 
        v-if="clearable && displayValue"
        name="x-circle"
        class="bx-cascader__clear"
        @click.stop="handleClear"
      />
    </div>

    <div 
      v-if="showDropdown"
      class="bx-cascader__dropdown bx-glass"
      :style="dropdownStyle"
    >
      <div class="bx-cascader__panel">
        <ul 
          v-for="(levelOptions, levelIndex) in panelOptions"
          :key="levelIndex"
          class="bx-cascader__menu"
        >
          <li 
            v-for="option in levelOptions"
            :key="option.value"
            :class="[
              'bx-cascader__menu-item',
              {
                'bx-cascader__menu-item--active': isOptionActive(option, levelIndex),
                'bx-cascader__menu-item--disabled': option.disabled
              }
            ]"
            @click="handleOptionClick(option, levelIndex)"
            @mouseenter="handleOptionHover(option, levelIndex)"
          >
            <span>{{ option.label }}</span>
            <BxIcon 
              v-if="option.children && option.children.length"
              name="chevron-right"
              class="bx-cascader__menu-item-arrow"
            />
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, nextTick } from 'vue'
import BxIcon from '../basic/BxIcon.vue'

export default {
  name: 'BxCascader',
  components: {
    BxIcon
  },
  props: {
    modelValue: {
      type: Array,
      default: () => []
    },
    options: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: false
    },
    expandTrigger: {
      type: String,
      default: 'click',
      validator: (value) => ['click', 'hover'].includes(value)
    },
    separator: {
      type: String,
      default: ' / '
    },
    size: {
      type: String,
      default: 'medium',
      validator: (value) => ['small', 'medium', 'large'].includes(value)
    }
  },
  emits: ['update:modelValue', 'change', 'expand'],
  directives: {
    clickOutside: {
      mounted(el, binding) {
        el.__clickOutsideHandler__ = (event) => {
          if (!(el === event.target || el.contains(event.target))) {
            binding.value(event)
          }
        }
        document.addEventListener('click', el.__clickOutsideHandler__)
      },
      unmounted(el) {
        document.removeEventListener('click', el.__clickOutsideHandler__)
      }
    }
  },
  setup(props, { emit }) {
    const showDropdown = ref(false)
    const selectedPath = ref([]) // 存储当前选中的路径，包含所有层级的选项

    // 初始化 selectedPath
    watch(() => props.modelValue, (newVal) => {
      if (newVal.length > 0) {
        // 根据 modelValue 找到对应的选项路径
        let currentOptions = props.options
        let path = []
        for (let i = 0; i < newVal.length; i++) {
          const found = currentOptions.find(opt => opt.value === newVal[i])
          if (found) {
            path.push(found)
            currentOptions = found.children || []
          } else {
            path = [] // 找不到则清空
            break
          }
        }
        selectedPath.value = path
      } else {
        selectedPath.value = []
      }
    }, { immediate: true })

    const displayValue = computed(() => {
      return selectedPath.value.map(item => item.label).join(props.separator)
    })

    const panelOptions = computed(() => {
      const panels = []
      let currentOptions = props.options
      
      panels.push(currentOptions)

      for (let i = 0; i < selectedPath.value.length; i++) {
        const selectedOption = selectedPath.value[i]
        if (selectedOption.children && selectedOption.children.length) {
          panels.push(selectedOption.children)
        } else {
          break // 如果没有子节点，则停止
        }
      }
      return panels
    })

    const dropdownStyle = computed(() => {
      // 动态计算下拉框位置，确保在视口内
      return {}
    })

    const toggleDropdown = () => {
      if (props.disabled) return
      showDropdown.value = !showDropdown.value
    }

    const handleClickOutside = () => {
      showDropdown.value = false
    }

    const handleOptionClick = (option, levelIndex) => {
      if (option.disabled) return

      // 更新 selectedPath
      selectedPath.value = selectedPath.value.slice(0, levelIndex)
      selectedPath.value.push(option)

      if (!option.children || option.children.length === 0) {
        // 最后一级，选中并关闭
        emit('update:modelValue', selectedPath.value.map(item => item.value))
        emit('change', selectedPath.value.map(item => item.value), selectedPath.value)
        showDropdown.value = false
      } else {
        // 非最后一级，展开下一级
        emit('expand', selectedPath.value.map(item => item.value), selectedPath.value)
      }
    }

    const handleOptionHover = (option, levelIndex) => {
      if (props.expandTrigger === 'hover' && !option.disabled) {
        // 更新 selectedPath
        selectedPath.value = selectedPath.value.slice(0, levelIndex)
        selectedPath.value.push(option)
        emit('expand', selectedPath.value.map(item => item.value), selectedPath.value)
      }
    }

    const handleClear = () => {
      selectedPath.value = []
      emit('update:modelValue', [])
      emit('change', [], [])
    }

    const isOptionActive = (option, levelIndex) => {
      return selectedPath.value[levelIndex] && selectedPath.value[levelIndex].value === option.value
    }

    return {
      showDropdown,
      selectedPath,
      displayValue,
      panelOptions,
      dropdownStyle,
      toggleDropdown,
      handleClickOutside,
      handleOptionClick,
      handleOptionHover,
      handleClear,
      isOptionActive
    }
  }
}
</script>

<style scoped>
.bx-cascader {
  position: relative;
  display: inline-block;
  width: 240px;
  font-family: var(--bx-font-family);
}

.bx-cascader--disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.bx-cascader__input {
  display: flex;
  align-items: center;
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-medium);
  background: var(--bx-glass-bg);
  backdrop-filter: var(--bx-glass-blur);
  transition: all var(--bx-transition-medium);
  cursor: pointer;
  padding: 8px 12px;
}

.bx-cascader__input:hover {
  border-color: var(--bx-glass-border-hover);
  background: var(--bx-glass-bg-hover);
}

.bx-cascader--focused .bx-cascader__input {
  border-color: rgba(0, 122, 255, 0.5);
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.1);
}

.bx-cascader__input-field {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  color: var(--bx-text-primary);
  font-size: inherit;
  cursor: inherit;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.bx-cascader__input-field::placeholder {
  color: var(--bx-text-tertiary);
}

.bx-cascader__arrow {
  font-size: 14px;
  color: var(--bx-text-secondary);
  transition: transform var(--bx-transition-medium);
}

.bx-cascader--focused .bx-cascader__arrow {
  transform: rotate(180deg);
}

.bx-cascader__clear {
  font-size: 14px;
  color: var(--bx-text-tertiary);
  cursor: pointer;
  margin-left: 8px;
}

.bx-cascader__clear:hover {
  color: var(--bx-text-primary);
}

.bx-cascader__dropdown {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  border: 1px solid var(--bx-glass-border);
  border-radius: var(--bx-radius-medium);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  animation: bx-fade-in-up 0.2s ease-out;
  display: flex;
  min-width: 200px;
}

.bx-cascader__panel {
  display: flex;
}

.bx-cascader__menu {
  list-style: none;
  padding: 4px 0;
  margin: 0;
  min-width: 120px;
  max-height: 200px;
  overflow-y: auto;
  border-right: 1px solid var(--bx-glass-border);
}

.bx-cascader__menu:last-child {
  border-right: none;
}

.bx-cascader__menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  cursor: pointer;
  color: var(--bx-text-primary);
  transition: background-color var(--bx-transition-fast);
}

.bx-cascader__menu-item--disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.bx-cascader__menu-item:hover:not(.bx-cascader__menu-item--disabled),
.bx-cascader__menu-item--active {
  background: var(--bx-glass-bg-hover);
}

.bx-cascader__menu-item-arrow {
  font-size: 12px;
  color: var(--bx-text-secondary);
}

@keyframes bx-fade-in-up {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bx-cascader {
    width: 100%;
  }
  
  .bx-cascader__dropdown {
    min-width: unset;
    width: 100%;
  }
  
  .bx-cascader__menu {
    min-width: unset;
    flex: 1;
  }
}
</style>

